<?php
/**
 * Created by xiaosong
 * E-mail:306027376@qq.com
 * Date: 2018/11/14
 * Time: 10:16
 */

namespace app\admin\controller;
use app\common\logic\Logic;
use app\common\logic\SkillForm;
use app\common\logic\SkillTag;
use app\common\model\Order;
use app\common\model\Skill as model;
use app\common\model\SkillApply;
use Qiniu\Auth;
use think\Db;
use think\Exception;

class Skill extends Base
{

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 技能列表
     */
    public function index()
    {

        $map = [];

        if (input('skill_name')) $map['skill_name'] = ['like','%'.trim(input('skill_name')).'%'];

        if(!isEmpty($_GET['type'])) $map['type'] = trim(input('type'));

        $model = new model();
        $rows  = $model->getList($map);
        $this->assign([
            'title' => '技能列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);

        return view();

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 技能编辑
     */
    public function edit()
    {

        /* 永不超时 */
        ini_set('max_execution_time', 0);

        $table = 'skill';
        $data = null;
        if (request()->isPost()){
            $data = input('post.');
//            $data['gift_id'] = implode(',',$data['gift_id']);

            $model = new Logic();

            $result = $model->saveChange($table,$data,'skill');

            if ($result){

                if (is_numeric($data['id'])){
                    $id = $data['id'];
                }else{
                    $id = $model->getLastInsID();
                }

                //添加更新形式
                $rows = [];

                $add  = [];
                $new  = 1;
                foreach ($data['form_name'] as $k => $v){
                    $arr = [];
                    $arr['form_name'] = $v;
                    $arr['form_id']   = $data['form_id'][$k];
                    $arr['skill_id']  = $id;
                    if ($arr['form_id']){
                        $arr['gift_id'] = implode(',',$data['form_id__'.$data['form_id'][$k]]);
                        $arr['mini_price'] = getMiniPrice($arr);
                        $rows[] = $arr;
                    }else{
                        $arr['gift_id'] = implode(',',$data['gift_new_'.$new]);
                        $arr['mini_price'] = getMiniPrice($arr);
                        $add[] = $arr;
                        $new ++;
                    }
                }

                $skill = new SkillForm();
                $map['skill_id'] = $id;
                $skill->where($map)->update(['skill_id'=>0]);

                if ($rows){
                    $skill->saveAll($rows);
                }

                if($add){
                    $skill->insertAll($add);
                }

                //添加更新标签
                $rows2 = [];
                $add2  = [];

                foreach ($data['tag_name'] as $k => $v){
                    $arr = [];
                    $arr['tag_name'] = $v;
                    $arr['tag']   = $data['tag'][$k];
                    $arr['skill_id']  = $id;
                    if ($arr['tag']){
                        $rows2[] = $arr;
                    }else{
                        $add2[] = $arr;
                    }
                }

                $tag = new SkillTag();
                $tag->where($map)->update(['skill_id'=>0]);

                if ($rows2){
                    $tag->saveAll($rows2);
                }

                if($add2){
                    $tag->insertAll($add2);
                }

                $column = $skill->where($map)->column('form_id');

                $form_id = implode(',',$column);

                $column2 = $tag->where($map)->column('tag');

                $tag = implode(',',$column2);

                $model->where($map)->update(['form_id'=>$form_id,'tag'=>$tag]);

                $this->success('操作成功',url('index'));
            }
            $this->error($model->getError());
        }

        $auth  = new Auth(config('qiniu')['ACCESSKEY'], config('qiniu')['SECRETKEY']);
        $token = $auth->uploadToken(config('qiniu')['bucket']);
        $domain = config('qiniu')['domain'];

        $gift = Db::name('gift')->order('price')->select();

        $this->_find($table);

        $this->assign([
            'title' => '技能编辑',
            'gift' => $gift,
            'token' => $token,
            'domain'=> $domain,
        ]);

        return view();

    }


    /**
     * 订单列表
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function order_list()
    {
        $map = [];

        if(!empty($_GET['start'])&&empty($_GET['end'])){
            $map['a.create_time'] = ['>=',strtotime($_GET['start'])];
        }elseif(!empty($_GET['end'])&&empty($_GET['start'])){
            $map['a.create_time'] = ['<=',strtotime($_GET['end'])];
        }elseif(!empty($_GET['start'])&&!empty($_GET['end'])){
            $map['a.create_time'] = ['between',array(strtotime($_GET['start']),strtotime($_GET['end']))];
        }

        if (is_numeric(input('uuid'))){
            $map['u.uuid|u.user_id'] =  input('get.uuid');
        }

        if (is_numeric(input('sd'))){
            $map['us.uuid|u.user_id'] =  input('get.sd');
        }

        if (is_numeric(input('skill_id'))){
            $map['a.skill_id'] =  input('get.skill_id');
        }

        if (is_numeric(input('status'))){
            $map['a.status'] =  input('get.status');
        }

        $model = new Order();

        $rows  = $model->getOrder($map);

        $total = $model->alias('a')->sum('price');

        $map['a.status'] = ['in',[4,5]];

        //完成订单
        $finish = $model->alias('a') ->join('skill s','s.skill_id = a.skill_id','LEFT')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('users us','us.user_id = a.to_user','LEFT')->where($map)->count();

        //进行中
        $map['a.status'] = ['in',[2,3]];
        $hand = $model->alias('a') ->join('skill s','s.skill_id = a.skill_id','LEFT')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('users us','us.user_id = a.to_user','LEFT')->where($map)->count();

        //废弃订单式
        $map['a.status'] = ['between',[6,11,12]];
        $wrong = $model->alias('a') ->join('skill s','s.skill_id = a.skill_id','LEFT')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('users us','us.user_id = a.to_user','LEFT')->where($map)->count();

        $this->assign([
            'title' => '技能列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'total' => $total,
            'finish' => $finish,
            'hand' => $hand,
            'wrong' => $wrong,
            'skills' => Db::name('skill')->select(),
            'status' => Order::$status,
        ]);

        return view();


    }






    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 更改状态
     */
    public function change()
    {
        $this->_change('skill');
    }

    public function delete()
    {
        $this->_del('skill');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户技能删除
     */
    public function del($id)
    {

        $info = Db::name('skill_apply')->find($id);

        try{
            Db::name('skill_apply')->delete($id);

            $map['user_id'] = $info['user_id'];
            $map['skill_id'] = $info['skill_id'];

            Db::name('skill_form_user')->where($map)->delete();
            Db::name('skill_tag_user')->where($map)->delete();

            $str = '您申请的技能['.getSkillName($info['skill_id']).']因:'.input('msg').';已被系统管理员删除.';
            \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除成功');

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 资质申请列表
     */
    public function apply()
    {

        cache('apply_history',request()->url());

        $map = [];

        if (input('skill_name')) $map['s.skill_name'] = ['like','%'.trim(input('skill_name')).'%'];

        if(!isEmpty($_GET['type'])) $map['s.type'] = trim(input('type'));

        if (!isEmpty(input('status'))){
            $map['a.status'] = trim(input('status'));
        }


        $model = new SkillApply();
        $rows  = $model->getList($map);
        $this->assign([
            'title' => '技能列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);

        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 资质申请审核
     */
    public function apply_edit()
    {

        $model = new SkillApply();

        $skill_apply = $model->getDetail(['a.apply_id'=>input('id')]);
        if (request()->isPost()){
            $data = input('post.');
            Db::startTrans();
            try{

                $info = Db::name('skill_apply')->find($data['id']);

                if (!$info){
                    $this->error('参数错误');
                }
                foreach ($data['forms_id'] as $k => $v){
                    $item['my_gift_id'] = implode(',',$data['forms_id_'.$v]);
                    $item['mini_price'] = getMiniPrice($item['my_gift_id']);
                    Db::name('skill_form_user')->where('id',$v)->update($item);
                }

                $map['status'] = $data['status'];
                $map['remark'] = $data['remark'];
                if (!is_numeric($data['id'])){
                    $this->error('参数错误');
                }
                $result = Db::name('skill_apply')->where('apply_id',$data['id'])->update($map);

                if ($result){

                    if ($data['status'] == 1){
                        //审核通过
                        $str = sprintf('您申请的技能 %s 已通过审核,现在开始接单吧!',$skill_apply['skill_name']);
                    }else{
                        //审核失败
                        if (!empty($data['remark'])){
                            $remark = ',驳回原因为:'.$data['remark'];
                        }else{
                            $remark = '.';
                        }
                        $str = sprintf('您申请的技能 %s 未通过审核%s',$skill_apply['skill_name'],$remark);
                    }
                    \app\api\controller\Base::sendUsrMsg('system',hashid($skill_apply['user_id']),$str);
                    $this->success('操作成功',cache('apply_history'));
                }else{
                    $this->error('操作失败');
                }

                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                api_return(0,$e->getMessage());
            }

        }

        $gift = Db::name('gift')->order('price')->select();
        $this->assign([
            'title' => '技能申请编辑',
            'data' => $skill_apply,
            'gift' => $gift,
        ]);
        return view();

    }


    protected static $payWay = [
//        '支付方式  1=>积分  2=>支付宝  3=>微信'
        1 => ['id'=>1,'cate_name'=>'积分'],
        2 => ['id'=>2,'cate_name'=>'支付宝'],
        3 => ['id'=>3,'cate_name'=>'微信'],
    ];

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单申诉
     */
    public function protest()
    {

        $map = [];

        $model = new Order();

        if (input('record') != 4){
            if (is_numeric(input('record'))){
                $map['a.record'] = input('record');
            }else{
                $map['a.record'] = 2;
            }
        }else{
            $map['a.record'] = ['in',[1,2]];
        }

        $rows = $model->getList($map);
        $this->assign([
            'title' => '订单申诉列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'payWay' => self::$payWay,
        ]);

        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 申诉审核
     */
    public function protest_edit()
    {
        if (request()->isPost()){
            $data = input('post.');
            $map['order_id'] = $data['id'];
            $map['status']   = 9;
            $order = Db::name('order')->where($map)->find();

            if (!$order) api_return(0,'申诉订单不存在');

            if ($data['status'] == 1){ //申诉成功

                $result = \app\api\controller\Base::refund($data['id'],11);
                Db::name('order')->where('order_id',$data['id'])->update(['record'=>1,'record_str'=>$data['record_str'],'update_time'=>time()]);
                if ($result === true){
                    $str = sprintf('订单编号:%s,申诉已%s:%s;',$data['id'],'通过',$data['record_str']);

                    \app\api\controller\Base::sendUsrMsg('system',[hashid($order['user_id']),hashid($order['to_user'])],$str);

                    $this->success('操作成功',url('protest'));
                }else{
                    $this->error($result);
                }
            }else{ //申诉失败
                $result = Db::name('order')->where('order_id',$data['id'])->update(['record_str'=>$data['record_str'],'status'=>10,'record'=>3,'update_time'=>time()]);

                if ($result !== false){
                    $str = sprintf('订单编号:%s,申诉已%s:%s;',$data['id'],'驳回',$data['record_str']);
                    \app\api\controller\Base::sendUsrMsg('system',[hashid($order['user_id']),hashid($order['to_user'])],$str);
                    $this->success('操作成功',url('protest'));
                }else{
                    $this->error('操作失败');
                }

            }



        }

        $model = new Order();

        $map['a.order_id'] = input('id');
        $data  = $model->getDetail($map);
        $data['protest'] = \app\api\controller\Base::staticInfo('nick_name,header_img,uuid,user_id',$data['user_id']);
        $data['user'] = \app\api\controller\Base::staticInfo('nick_name,header_img,uuid,user_id',$data['to_user']);
        $this->assign([
            'title' => '申诉审核',
            'data' => $data,
        ]);
        return view();

    }



}